from datetime import datetime
from sqlalchemy import Boolean, Column, DateTime, Integer, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

from config.settings import Settings

settings = Settings()

engine = create_engine(settings.HCO_DB_PGSQL, pool_size=10, max_overflow=20)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


class Entity(Base):
    __abstract__ = True

    id = Column(Integer, primary_key=True, index=True)
    creator_id = Column(Integer)
    updater_id = Column(Integer)
    create_time = Column(DateTime, default=datetime.now)
    update_time = Column(DateTime, default=datetime.now)
    is_deleted = Column(Boolean, default=False)

    def delete(self, user_id):
        self.is_deleted = True
        self.set_update_operation(user_id)

    def set_add_operation(self, user_id):
        self.creator_id = user_id
        self.create_time = datetime.now()
        self.updater_id = user_id
        self.update_time = datetime.now()

    def set_update_operation(self, user_id):
        self.updater_id = user_id
        self.update_time = datetime.now()
